//
//  SwiftTool.swift
//  SwiftTool
//
//  Created by 红沙尘 on 2018/11/4.
//  Copyright © 2018年 红沙尘. All rights reserved.
//

import UIKit
import SwiftKeychainWrapper

class SwiftTool: NSObject {

    //安全字符串
    class func safe(str: Any?) -> String {
        return str as? String ?? ""
    }
    
    class func saveAccount() {
        
        //保存敏感信息
        KeychainWrapper.standard.set("phone", forKey: "key")
        
        //读取敏感信息
        _ = KeychainWrapper.standard.string(forKey: "key")
        
        //移除所有敏感信息
        _ = KeychainWrapper.standard.removeAllKeys()
    }
    
    /// 获取项目版本号(version)
    ///
    /// - Returns: 目版本号(version)
    class func app_version() -> String {
        let infoDic = Bundle.main.infoDictionary
        let version:String = infoDic?["CFBundleShortVersionString"] as! String
        return version
    }
    
    //MARK: - NSString -> NSDictionary
    
    /// 字符串转换为字典
    ///
    /// - Parameter jsonString: JSON格式的字符串
    /// - Returns: 字典
    class func dictionaryByString(jsonString:String) -> NSDictionary{
        
        let jsonData:Data = jsonString.data(using: .utf8)!
        
        let dict = try? JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers)
        if dict != nil {
            return dict as! NSDictionary
        }
        return NSDictionary()
    }
    
    //MARK: - NSDictionary -> NSString
    
    /// 字典转换为字符串
    ///
    /// - Parameter dictionary: 字典
    /// - Returns: JSON格式的字符串
    class func stringByDictionary(dictionary:NSDictionary) -> NSString {
        if (!JSONSerialization.isValidJSONObject(dictionary)) {
            print("无法解析出JSONString")
            return ""
        }
        let data : NSData! = try! JSONSerialization.data(withJSONObject: dictionary, options: []) as NSData?
        let JSONString = NSString(data:data as Data,encoding: String.Encoding.utf8.rawValue)
        return JSONString!
    }
}
